import React from 'react';
import { connect } from 'dva';
import { Table, Button, Icon } from 'antd';
import { Link } from 'dva/router';
import _ from 'lodash';
import Modal from './modal';
import { getCol } from './col';

const styles = require('../app.less');

const namespace = 'task';

class Task extends React.Component {
  constructor(p) {
    super(p);
    this.queryData = this.queryData.bind(this);// 查询
    this.action = this.action.bind(this);
    this.changeState = this.changeState.bind(this); // 改变task的状态
    this.state = {
      type: null,
      loadingId: null, // 正在操作的task
    };
  }

  componentDidMount() {
    this.queryData();
  }

  /**
   * 获取操作按钮
   */
  getOp() {
    return {
      title: '操作',
      key: 'op',
      render: (text, record) => {
        const state = _.get(record, 'state');
        const id = record.id;
        const loadingId = _.get(this, 'state.loadingId');
        // 下一状态
        const nextState = {
          ready: 'open',
          open: 'close',
          close: 'ready',
        };
        // 连接
        const link = txt => <a key={txt} onClick={this.changeState(nextState[state], id)}>{txt}</a>;
        const stateBtn = {
          open: link('停止'),
          close: link('准备'),
          ready: link('开始'),
        };

        const { loading } = this.props;
        const stateLoading = loading.effects[`${namespace}/changeState`];
        return (
          <div>
            <a
              onClick={this.action('edit', record)}
            >编辑</a>
            &nbsp;|&nbsp;
            {
            [
              (stateLoading && loadingId === record.id) && <Icon style={{ color: 'blue' }} type="loading" />,
              stateBtn[state],
            ]
            }
            &nbsp;|&nbsp;
            <Link to={`/record?taskId=${id}`}>查看</Link>
          </div>
        );
      },
    };
  }

  action(type, item) {
    return () => {
      this.setState({
        type,
        record: item,
      });
      // 重新加载数据
      if (!type) {
        this.queryData();
      }
    };
  }

  // 改变一个任务的状态
  changeState(state, id) {
    return () => {
      const { dispatch } = this.props;
      this.setState({
        loadingId: id,
      });
      dispatch({
        type: `${namespace}/changeState`,
        payload: {
          state, id,
        },
      });
    };
  }

  // 查询数据
  queryData() {
    const { dispatch, location } = this.props;
    const query = location.query;
    dispatch({
      type: `${namespace}/query`,
      payload: {
        user: query.user,
        mode: query.mode,
      },
    });
  }

  render() {
    const { task, loading } = this.props;
    const { keys, tasks } = task;
    const columns = getCol(keys);
    if (!columns.find(item => item.key === 'op')) {
      columns.push(this.getOp());
    }

    return (
      <div className={styles.container}>
        {
          this.state.type && (
            <Modal
              visible={Boolean(this.state.type)}
              record={this.state.record}
              onFinish={this.action(null, null)}
              loading={loading}
              type={this.state.type}
            />
          )
        }
        <h2>任务管理</h2>

        <h3>操作：</h3>
        <Button
          type="primary"
          onClick={this.action('create')}
        >
          <Icon type="plus" />添加任务
        </Button>
        &nbsp;&nbsp;
        <br />
        <br />
        <h3>任务列表：</h3>
        <Table
          columns={columns}
          dataSource={tasks.sort((a, b) => Number(b.id) - Number(a.id))}
          loading={loading.effects['task/query']}
          rowKey="id"
        />
      </div>
    );
  }
}

export default connect(state => state)(Task);
